<?php
//$worker = [];
//for ($i = 0; $i < 3; $i++) {
//   $process = new \Swoole\Process(function (\Swoole\Process $worker) {
//        $data = $worker->read();
//        echo "来自主进程的数据：{$data}\n";
//        $worker->write("来自id为 {$worker->pid} 的数据，你好!");
//   });
//   $process->start();
//   $worker[$process->pid] = $process;
//}
//
//foreach ($worker as $pid => $process) {
//    $process->write("进程{$pid}你好我是主进程");
//    $data = $process->read();
//    echo "{$data}\n";
//}


//$process1 = new Swoole\Process(function (Swoole\Process $worker) {
//    while(1){
//        $data = $worker->read();
//        if($data){
//            echo "Child {$worker->pid}：接收到的数据 - \"{$data}\"。", PHP_EOL;
//        }
//    }
//});
//$process1->start();
//
//$messages = [
//    "Hello World!",
//    "Hello Cat!",
//    "Hello King",
//    "Hello Leon",
//    "Hello Rose"
//];
//$process2 = new Swoole\Process(function (Swoole\Process $worker) use($process1, $messages) {
//    foreach($messages as $msg){
//        sleep(1);
//        $process1->write("来自 {$worker->pid} {$msg} ！");
//    }
//    sleep(1);
//    $worker->kill($process1->pid, SIGKILL);
//});
//$process2->start();
//\Swoole\Process::wait(true);
//\Swoole\Process::wait(true);


//$workers = [];
//for ($i = 1; $i < 3; $i++) {
//    $process = new Swoole\Process(function (Swoole\Process $worker) {
//        $socket = $worker->exportSocket();
//        $data = $socket->recv();
//        echo "Child {$worker->pid}：来自 Master 的数据 - \"{$data}\"。", PHP_EOL;
//        $socket->send("发送给领导，来自 {$worker->pid} 的数据，通过管道 {$worker->pipe} ！");
//    }, false, SOCK_DGRAM, true);
//    $process->start();
//    $workers[$process->pid] = $process;
//}
//foreach ($workers as $pid => $process) {
//    \Swoole\Coroutine\run(function () use ($pid, $process) {
//        $socket = $process->exportSocket();
//        $socket->send("{$pid}，你好！");
//        $data = $socket->recv();
//        echo "Master：来自子进程 {$pid} 的数据 - \"{$data}\"", PHP_EOL;
//    });
//}
//foreach ($workers as $pid => $worker) {
//    \Swoole\Process::wait();
//}


for ($i = 1; $i < 3; $i++) {
    $process = new Swoole\Process(function (Swoole\Process $worker) {
        while($msg = $worker->pop()) {
            if ($msg === false) {
                break;
            }
            echo "Child {$worker->pid}：来自 Master 的数据 - \"{$msg}\"。", PHP_EOL;
            sleep(1);
        }
    });
    $process->useQueue(1, 2);
    // $process->useQueue(1, 1);
//     $process->useQueue(1, 1 | \Swoole\Process::IPC_NOWAIT);
    $process->start();
}
$messages = [
    "Hello World!",
    "Hello Cat!",
    "Hello King",
    "Hello Leon",
    "Hello Rose"
];

foreach ($messages as $msg){
    $process->push($msg);
}

\Swoole\Process::wait(true);
\Swoole\Process::wait(true);